// 引入配置
const {
	CODE,
	SERVER,
	TIP
} = require("./config.js");
import toast from "./toast.js";
import Request from 'luch-request' // 使用npm
import {
	removeToken
} from "@/utils/storage.js"
import {
	autoLogin
} from "@/utils/autoLogin.js"

const http = new Request()
/**
 * @description 修改全局默认配置
 * @param {Function}   
 */
http.setConfig((config) => {
	/* config 为默认全局配置*/
	config.baseURL = SERVER; /* 根域名 */
	return config
})

http.interceptors.request.use((config) => { // 可使用async await 做异步操作
	let token = uni.getStorageSync('token')
	config.header = {
		'X-Requested-With': 'XMLHttpRequest',
		'token': token,
		'Accept': "application/json",
		'sessionType': 'header'
	}
	uni.showNavigationBarLoading();

	return config
}, config => { // 可使用async await 做异步操作
	return Promise.reject(config)
})

http.interceptors.response.use((response) => {
	if (response.data.code == CODE.SUCCESS) { //状态码0
		uni.hideNavigationBarLoading();
		return Promise.resolve(response.data)
	} else if (response.data.code == CODE.EXCEPTION) { //状态码2020
		uni.hideNavigationBarLoading();
		return Promise.reject(response.data)
	} else if (response.data.code == CODE.UNLOAD) { //状态码5001
		removeToken()
		uni.showModal({
			title: '提示',
			content: '用户登录已失效，请点击重新登录',
			showCancel: false,
			success: function(res) {
				autoLogin().then(res => {
					uni.switchTab({
						url:'/pages/index/index'
					})
				})
			},
			fail: function(res) {
				uni.switchTab({
					url:'/pages/index/index'
				})
			},

		});
		uni.hideNavigationBarLoading();
		return Promise.reject(response.data)
	} else {
		toast.tip(response.data.message);
		uni.hideNavigationBarLoading();
		return Promise.reject(response.data)
	}

	// return response
}, (error) => {
	/*  对响应错误做点什么 （statusCode !== 200）*/
	console.log('------打印请求抛出错误信息--------', error)
	toast.hideLoading();
	uni.hideNavigationBarLoading();
	toast.tip(TIP);
	return Promise.reject(error)
})

export default http